package com.zuipin.quartz;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.zuipin.entity.product.ProductExtInfo;
import com.zuipin.service.IProductExtInfoService;
import com.zuipin.util.DateUtils;

/**
 * 自动上、下架商品
 * @author huihang
 *
 */
@Configuration
public class ProductTimingShelfJob extends QuartzJobBean {
	@Resource
	private IProductExtInfoService	productExtInfoService;
	private Logger					log	= Logger.getLogger(ProductTimingShelfJob.class);
	
	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		// TODO Auto-generated method stub
		log.info("自动上架商品--定时器---start----" + DateUtils.getCurrentDateTime());
		// 查询上架List
		List<Map<String, Object>> onList = productExtInfoService.canOnShelf(DateUtils.getCurrentDateTime());
		if (onList != null && onList.size() > 0) {
			for (Map<String, Object> map : onList) {
				int i = compare_date(String.valueOf(map.get("onShelfTime")), DateUtils.getCurrentDateTime());
				if (i < 0) {
					// 判断(内部已经判断)是否可以上架
					productExtInfoService.productShelf(Long.valueOf(String.valueOf(map.get("proExtId"))), Long.valueOf(String.valueOf(map.get("sysId"))), ProductExtInfo.ON_SHELF,
							null);
				}
			}
		}
		log.info("自动上架商品--定时器---end----" + DateUtils.getCurrentDateTime());
		
		log.info("--------------------------------------------------------------------");
		
		log.info("自动下架架商品--定时器---start----" + DateUtils.getCurrentDateTime());
		// 查询下架List
		List<Map<String, Object>> offList = productExtInfoService.canOffShelf(DateUtils.getCurrentDateTime());
		if (offList != null && offList.size() > 0) {
			for (Map<String, Object> map : offList) {
				int i = compare_date(String.valueOf(map.get("offShelfTime")), DateUtils.getCurrentDateTime());
				if (i < 0) {
					productExtInfoService.productShelf(Long.valueOf(String.valueOf(map.get("proExtId"))), Long.valueOf(String.valueOf(map.get("sysId"))), ProductExtInfo.OFF_SHELF,
							null);
				}
			}
		}
		log.info("自动下架商品--定时器---end----" + DateUtils.getCurrentDateTime());
		
	}
	
	public int compare_date(String date1, String date2) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date dt1 = null;
		Date dt2 = null;
		try {
			dt1 = sdf.parse(date1);
			dt2 = sdf.parse(date2);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			log.info("自动上下架商品" + e.getMessage());
		}
		
		if (dt1.getTime() < dt2.getTime()) {
			System.out.println("dt1在dt2之前");
			return -1;
		} else if (dt1.getTime() > dt2.getTime()) {
			System.out.println("dt1在dt2之后");
		}
		return 0;
	}
	
}
